package com.txzt.gaea.business.plan.service.impl;

import com.txzt.gaea.api.client.AdminUserRemoteService;
import com.txzt.gaea.business.fund.domain.model.FundIssued;
import com.txzt.gaea.business.plan.domain.model.PlanIssue;
import com.txzt.gaea.business.plan.service.IPlanIssueService;
import com.txzt.gaea.business.sequence.service.ISequenceService;
import com.txzt.gaea.common.base.service.impl.BaseServiceImpl;
import com.txzt.gaea.common.core.base.context.AdminUserContext;
import com.txzt.gaea.common.enums.*;
import com.txzt.gaea.dto.UserSingleDetailQueryDTO;
import com.txzt.gaea.upgrade.project.domain.model.ProjectMain;
import com.txzt.gaea.vo.AdminUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PlanIssueServiceImpl extends BaseServiceImpl<PlanIssue> implements IPlanIssueService {

    @Autowired
    private AdminUserRemoteService adminUserRemoteService;
    @Autowired
    private ISequenceService sequenceService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean assignAndCompletion(Integer pageNumber,Integer pageSize,Long departId, Long projectLeader, String ids) {
        AdminUserVO adminUserVO = AdminUserContext.getUser();
        List<PlanIssue> targetList = new ArrayList<>();
//        List<ProjectMain> projectMainList = new ArrayList<>();
        List<Long> uids= Arrays.stream(ids.split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList());
        List<PlanIssue> list = sqlManager.query(PlanIssue.class)
                .andEq("plan_status", IssueStatus.TODO.getCode())
                .andEq("create_by", adminUserVO.getId())
                .andEq("is_delete", IsDeleteEnum.NOTDELETE.getCode())
                .andIn("id",uids)
                .orderBy("id desc")
                .limit(pageNumber,pageSize)
                .select();
        list.forEach(source -> {
            PlanIssue target = new PlanIssue();
            target.setId(source.getId());
            target.setPlanStatus(IssueStatus.DONE.getCode());
            target.setUpdateBy(adminUserVO.getId());
            target.setUpdateTime(new Date());
            if (null == source.getDepartId()) {
                target.setDepartId(departId);
            }
            if (null == source.getProjectLeader()) {
                target.setProjectLeader(projectLeader);
            }
            targetList.add(target);
            // 新增项目
            ProjectMain projectMain = new ProjectMain();
            BeanUtils.copyProperties(source,projectMain);
            projectMain.setId(null);
            projectMain.setIssueId(source.getId());
            projectMain.setCreateBy(null == source.getProjectLeader() ? projectLeader : source.getProjectLeader());
            projectMain.setDepartId(null == source.getDepartId() ? departId : source.getDepartId());
            projectMain.setProjectLeader(null == source.getProjectLeader() ? projectLeader : source.getProjectLeader());
            projectMain.setCreateTime(new Date());
            projectMain.setUpdateBy(null);
            projectMain.setUpdateTime(null);
            //获取责任所在部门为项目提报部门
            UserSingleDetailQueryDTO userSingleDetailQueryDTO = new UserSingleDetailQueryDTO();
            userSingleDetailQueryDTO.setUserId(projectMain.getProjectLeader());
            projectMain.setDeptId(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getDeptid());
            projectMain.setProjectNode(null);
            projectMain.setProjectStatus(null);
            projectMain.setGlobalStatus(GlobalStatus.INIT.getCode());
            projectMain.setDataStatus(null);
            projectMain.setFlowStatus(null);
            projectMain.setProgressStatus(ProgressStatus.DOING.getCode());
            //projectMainList.add(projectMain);
            sqlManager.insertTemplate(projectMain,true);
            //20221114-018 计划下达后，同步再经费下达列表生成一条记录，避免项目遗漏
            FundIssued fundIssued = new FundIssued();
            fundIssued.setWriteBy(adminUserVO.getId());
            fundIssued.setDeptId(adminUserVO.getDeptid());
            fundIssued.setWriteTime(new Date());
            fundIssued.setStatus(FundIssuedStatus.UN_SUBMIT.getCode());
            fundIssued.setProjectId(projectMain.getId());
            fundIssued.setPlanBudget(projectMain.getBudgetFund());
            fundIssued.setProjectNo(projectMain.getPlanNo());
            fundIssued.setProjectName(projectMain.getProjectName());
            fundIssued.setApplyNo(createApplyNo());
            sqlManager.insertTemplate(fundIssued,true);
        });
        int[] count = sqlManager.updateBatchTemplateById(PlanIssue.class,targetList);
        //sqlManager.insertBatch(ProjectMain.class,projectMainList);
        return count.length == list.size();
    }

    @Override
    public List<PlanIssue> selectByNo(PlanIssue query) {
        List<PlanIssue> select = sqlManager.lambdaQuery(PlanIssue.class).andNotEq(PlanIssue::getId,query.getId()).andEq(PlanIssue::getPlanNo, query.getPlanNo()).andEq(PlanIssue::getIsDelete, IsDeleteEnum.NOTDELETE.getCode()).select();
        return select;
    }
    private String createApplyNo(){
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);
        Integer sequence = sequenceService.getSequence("fund_issued", "apply_no");
        return year + "JFXD" + String.format("%03d", sequence);
    }
}
